<template>
  <a-card :bordered="false">
    <h3>消息推送</h3>
    <MarketingFilter ref="filter" :type="2" @onAddMessage="handleAddMessage" @onSearch="onSearch"></MarketingFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="content" slot-scope="record">
        <a-popover :overlayStyle="{ width: '380px', height: 'auto' }">
          <template slot="content">
            <p style="word-break: break-all;">{{ record.advicesContent }}</p>
          </template>
          <span class="remarks">{{ record.advicesContent }}</span>
        </a-popover>
      </span>
      <span slot="member" slot-scope="record">
        <template v-if="record.sendObject == 2">
          <p v-for="(item, index) in record.sendObjectUserList.slice(0, 5)" :key="index">{{ item.userNickname}}/{{item.phone}}(社区ID：{{item.communityId}})</p>
          <a @click="handleShowMember(record.id)" v-if="record.sendObjectUserList.length > 5">查看更多</a>
        </template>
        <template v-if="record.sendObject == 0">全部用户</template>
        <template v-if="record.sendObject == 1">
          {{record.sendObjectIdentityList.map(e => e.identityName).join('、')}}
        </template>
      </span>
      <span slot="sendWay" slot-scope="record">
        <span v-if="record.sendWay == 0">立即发送</span>
        <span v-if="record.sendWay == 1">定时发送</span>
      </span>
      <span slot="action" slot-scope="record">
        <a v-if="activeKey==1" @click="handleMessageDetails(record.id)">查看</a>
        <a v-if="activeKey==0" @click="handleEditMessage(record.id)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确认要删除该条消息吗？" ok-text="确定" cancel-text="暂不" @confirm="handleAdvicesDelete(record.id)">
          <a>删除</a>
        </a-popconfirm>
      </span>
    </s-table>
    <a-modal title="" :visible="memberVisible" width="500px"  :footer="null" @cancel="memberVisible = false" >
    <!-- :pagination="pagination" @change="handleSendUserChange" -->
      <!-- <a-table style="margin-top: 20px;" size="small"  :pagination="pagination"  :columns="memberColumns" :data-source="userIdentityListDtoList" :rowKey="(record, index) => index" >
        <span slot="index" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="memberInfor" slot-scope="text, record, index">
          社区昵称/15598983234（社区ID：983）
        </span>
      </a-table> -->
      <div style="height: 320px;"><SendUser :isDetails="true" v-if="id" :id="id"></SendUser></div>
    </a-modal>
  </a-card>
</template>
<script>
import { advicesList, advicesDelete, advicesDetail, sendCount} from '@/api/micromall/communityMarketing'
import { STable } from '@/views/box/components'
import MarketingFilter from '../../components/MarketingFilter'
import { columns, memberColumns } from '../marketingManagement/messageList.js'
import SendUser from '../../components/SendUser'
const tabList = [
        {
          name: '已发送',
          status: '1'
        },
        {
          name: '尚未发送',
          status: '0'
        }
      ]
export default {
  components: {
    MarketingFilter,
    STable,
    SendUser
  },
  data() {
    return {
      id: '',
      userIdentityListDtoList: [],
      memberVisible: false,
      sendUserList: [
        {id: 1}
      ],
      memberColumns,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      sort: '',
      tabList,
      activeKey: tabList[0].status,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          ...this.queryParam,
         current: parameter.pageNo,
          size: parameter.pageSize,
          isSend: this.isSend
        }
        return advicesList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  activated() {
    this.getCount()
  },
  computed: {},
  mounted() {},
  watch: {
    $route(to, from) {
      const whiteList = [
        '/micromall/community/marketingManagement/addOrEditMessage/',
        '/micromall/community/marketingManagement/messageTypeList'
        ]
      const currentPathBase = '/micromall/community/marketingManagement/messageList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          this.activeKey = this.tabList[0].status
          this.tabChange(this.activeKey) // 刷新当前页面
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/marketingManagement/messageList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 获取状态数量
    getCount() {
      if (this.requestFlag()) return
      sendCount().then(res => {
        if (res.code === 200) {
          const {unSent, sent} = res.data
          this.tabList[0].name = `已发送（${sent || 0}）`
          this.tabList[1].name = `尚未发送（${unSent || 0}）`
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 查看更多发送对象
    handleShowMember(id) {
      this.id = ''
      const data = {
        id,
        current:1
      }
      advicesDetail(data).then(res => {
        if (res.code == 200) {
          this.memberVisible = true
          this.id = id
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    
    // handleSendUserChange(pagination) {
    //   const pager = { ...this.pagination }
    //   pager.current = pagination.current
    //   this.pagination = pager
    //   this.getSendUserList()
    // },

    // 新增消息
    handleAddMessage(v) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditMessage/${v}`)
    },

     // 编辑消息
    handleEditMessage(id) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditMessage/${id}`)
    },

    // 删除
    handleAdvicesDelete(id) {
      const data = {
        id
      }
      advicesDelete(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 消息详情
    handleMessageDetails(id) {
      this.$router.push(`/micromall/community/marketingManagement/messageDetails/${id}`)
    },

    tabChange(activeKey) {
      this.$nextTick(() => {
        this.activeKey = activeKey
        this.isSend = activeKey
        this.$refs.filter.reset()
      })
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    handleSubmitSort() {}
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
</style>
